/************************************************************************
* View class, handle display, graphics effect, using model. 
* Author : Shaolan
* Version : 1.0
* Website : http://shaolan.net
*/
#include "view.hpp"


// DEBUG FUNCTION
void printV(const char * s) {
	pspDebugScreenSetXY(0,0);
	pspDebugScreenPrintf(s);
}

// ***********************************************************************************************************************************
// Public Constructor
View::View(){
	setModel(NULL);
	setTemplate(NULL);
}

View::View(Model * m){
	setModel(m);
	setTemplate(NULL);
}

View::View(Model * m,Template * t){
	setModel(m);
	setTemplate(t);
}

// ***********************************************************************************************************************************
// Public destructor
View::~View(){
}

// ***********************************************************************************************************************************
// Getters
Model * View::getModel() const {return model; }
Template * View::getTemplate() const { return tpl; }

// ***********************************************************************************************************************************
// Setters
void View::setModel(Model * m) { model = m; }
void View::setTemplate(Template * t) { tpl = t; }

// ***********************************************************************************************************************************
// Draw method

// Draw the list of falling item
void View::drawBlock(std::list<Block> * l){
	for (std::list<Block>::iterator i = l->begin() ; i != l->end() ; i++)
		drawBlock(&(*i));
}

// Draw the given falling item
void View::drawBlock(Block * i){
	int k = i->start , j = 0;
	do {
		geDrawImage(i->x+((j%2)*20),i->y+((j>2 ? 1 : 0)*20),tpl->getResource(i->data[k]));
		k == 3 ? k = 0 : k++;
	} while ( ++j < 4 );
}

// Draw all the view
void View::draw(){
	// Draw template
	if (tpl == NULL) return;
	tpl->draw();
	// Draw items
	for (int i = 0 ; i < model->getWidth() ; i++){
		for (int j = 0 ; j < model->getHeight() ; j++){
			if (model->getMapping(i,j) != EMPTY)
				geDrawImage(40+(i*20),26+(j*20),tpl->getResource(model->getMapping(i,j)));
	}}
	// Draw Next Block
	drawBlock(model->getNext());
	// Draw Falling Block
	drawBlock(model->getFalling());
	geSwapBuffers();
}